<?php

namespace App\Models\Train\TrainTripInfo\Repositories;

use App\Models\Train\TrainTripInfo\TrainExitingPort;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Facades\Cache;

class TrainExitingPortRepository extends BaseRepository implements Interfaces\TrainExitingPortRepositoryInterface
{
    public function __construct(TrainExitingPort $exitingPort)
    {
        parent::__construct($exitingPort);
    }

    public function addPort(array $data): TrainExitingPort
    {
        $port = $this->findOneByTrainAndStation($data['train_code'], $data['to_station_code']);
        if ($port) {
            $this->update($data, $port);
            return $port;
        }
        return $this->create($data);
    }

    public function findOneByTrainAndStation(string $train_code, string $to_station_code): ?TrainExitingPort
    {
        $cache_key = "Train:ExitingPort:{$train_code}:{$to_station_code}";
        if (Cache::has($cache_key)) {
            $port = Cache::get($cache_key);
            if ($port instanceof TrainExitingPort) {
                return $port;
            } else {
                Cache::forget($cache_key);
            }
        }
        $port = $this->findOneBy([
            'train_code'      => $train_code,
            'to_station_code' => $to_station_code,
        ]);

        if ($port instanceof TrainExitingPort) {
            Cache::put($cache_key, $port, 10 * config('trip.ttl.day'));
        }
        return $port;
    }
}